﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace HDUSampling.HDUControls.HTools.LoadingFrm
{
    public class BusyUtil
    {
        public BusyUtil(Grid _grid)
        {
            grid = _grid;
            busy = new Grid();
            busy.VerticalAlignment = grid.VerticalAlignment;
            busy.HorizontalAlignment = grid.HorizontalAlignment;
            busy.Margin = grid.Margin;
            busy.Width = grid.Width;
            busy.Height = grid.Height;
            DependencyObject parent = GetParentObject(grid);
            ((Grid)parent).Children.Add(busy);
        }
        public void Start(int MSecond)
        {
            ShowBusy();
            syn = SynchronizationContext.Current;
            Thread th = new Thread(() => {
                Thread.Sleep(MSecond);
                syn.Post(CloseBusy, null);
            });
            th.Start();
        }
        BusyDecorator busyc = null;
        SynchronizationContext syn = null;
        Grid grid = null;
        Grid busy = null;
        public void ShowBusy()
        {
            grid.Visibility = System.Windows.Visibility.Hidden;
            busy.Visibility = System.Windows.Visibility.Visible;
            busyc = new BusyDecorator();
            busyc.Margin = new System.Windows.Thickness(0);
            busyc.IsBusy = true;
            busy.Children.Add(busyc);
        }
        public void CloseBusy(object ob)
        {
            busyc.IsBusy = false;
            busy.Children.Clear();
            grid.Visibility = System.Windows.Visibility.Visible;
            busy.Visibility = System.Windows.Visibility.Hidden;
            DependencyObject parent = GetParentObject(grid);
            ((Grid)parent).Children.Remove(busy);
        }
        public  DependencyObject GetParentObject(DependencyObject child)
        {
            // get parent item
            DependencyObject parentObject = VisualTreeHelper.GetParent(child);

            // if parent is not found, search for parent using logical tree
            if (parentObject == null)
            {
                // if this is a content element, try to get parent through content property
                ContentElement contentElement = child as ContentElement;
                if (contentElement != null)
                {
                    parentObject = ContentOperations.GetParent(contentElement);
                }
            }
            return parentObject;
        }
    }
}
